package cn.itsource.exception;

import cn.itsource.enums.GlobalExceptionEnum;
import cn.itsource.result.JSONResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * 全局异常处理
 */

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(CustomGlobalException.class)
    public JSONResult customGlobalExceptionHandler(CustomGlobalException e){
        e.printStackTrace();
        return JSONResult.error(e.getMessage());
    }


    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JSONResult methodArgumentNotValidException(MethodArgumentNotValidException e){
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        StringBuffer stringBuffer = new StringBuffer();
        allErrors.forEach(error->{
            stringBuffer.append(error.getDefaultMessage()+";");
        });

        return JSONResult.error(stringBuffer.toString(),GlobalExceptionEnum.PARAM_NOT_VALID.getCode());
    }


    @ExceptionHandler(Exception.class)
    public JSONResult exceptionHandler(Exception e){
        e.printStackTrace();
        return JSONResult.error(GlobalExceptionEnum.GLOBAL_EXCEPTION.getMessage(),
                GlobalExceptionEnum.GLOBAL_EXCEPTION.getCode());
    }

}
